package cn.ac.sec.oil.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import cn.ac.sec.framework.db.SqlUtils;
import cn.ac.sec.oil.data_analysis.protocol.ProtocolAnalysis;

/**
 * 功能：当socket建立连接或接收到消息时触发调用
 */
public class NettyServerHandlerTest extends ChannelInboundHandlerAdapter {

	public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println(bytesToHexString(req));
	}

	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) // flush掉所有写回的数据
		        .addListener(ChannelFutureListener.CLOSE); // 当flush完成后关闭channel
	}

	private static final Logger LOG = Logger.getLogger(NettyServerHandlerTest.class);
	ProtocolAnalysis pAnalysis = new ProtocolAnalysis(); // 数据协议解析与处理模块
	String[] result = new String[4]; // 用于保存数据的处理结果，分为2个部分

	/*
	 * 覆盖 channelActive方法 在channel被启用的时候触发 (在建立连接的时候) 不能随便向设备发送数据
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {

		LOG.info(ctx.channel().remoteAddress() + "连入服务器！");
		// ctx.writeAndFlush("Welcome to " +
		// InetAddress.getLocalHost().getHostName() + " service!\n");

		super.channelActive(ctx);
	}

	/**
	 * 功能：处理设备掉线等异常
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

		ctx.flush();
		LOG.info(ctx.channel().remoteAddress() + "异常离线 ...");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {

		LOG.info(ctx.channel().remoteAddress() + "离线 ...");
	}
	
	public static String bytesToHexString(byte[] src){  
	    StringBuilder stringBuilder = new StringBuilder("");  
	    if (src == null || src.length <= 0) {  
	        return null;  
	    }  
	    for (int i = 0; i < src.length; i++) {  
	        int v = src[i] & 0xFF;  
	        String hv = Integer.toHexString(v);  
	        if (hv.length() < 2) {  
	            stringBuilder.append(0);  
	        }  
	        stringBuilder.append(hv);  
	    }  
	    return stringBuilder.toString();  
	}  
}
